<template>
  <div>
    <el-row class="config-box">
      <el-col :span="5" :offset="2">
        <Card cardWidth='100%' :scalable="false" cardName="配置项">
          <div slot="content">
            <div class="input-item">
              <h3 class="h3-type">图片对应的文章类型</h3>
              <el-radio-group v-model="entity.imageType" v-if="entity.id === 0">
                <el-radio-button :label="1">站内文章</el-radio-button>
                <el-radio-button :label="2">外链文章</el-radio-button>
              </el-radio-group>
              <el-tooltip v-else effect="dark" content="编辑模式下不能修改文章类型" placement="top">
                <el-radio-group v-model="entity.imageType">
                  <el-radio-button :label="1" disabled>站内文章</el-radio-button>
                  <el-radio-button :label="2" disabled>外链文章</el-radio-button>
                </el-radio-group>
              </el-tooltip>

            </div>
            <div class="input-item">
              <h3 class="h3-type">是否启用</h3>
              <div class="radio-box">
                <el-radio v-model="entity.usable" :label="1">启用</el-radio>
                <el-radio v-model="entity.usable" :label="0">不启用</el-radio>
              </div>
            </div>
            <div class="input-item">
              <h3 class="h3-sort">排序优先级</h3>
              <el-input
                class="input-sort"
                v-model="entity.sort"
                maxLength="2"
                @focus="focusSortInput"
                @blur="blurSortInput"></el-input>
              <span :class="sortTipFlag?'tip tip-sort showTip': 'tip tip-sort'">输入1~99范围内的整数，值越小优先级越高</span>
              <span class="star sort-star">*</span>
            </div>
            <div class="input-item">
              <h3 class="h3-expire">自动过期</h3>
              <el-checkbox class="expire-checkbox" v-model="expireFlag">启用自动到期</el-checkbox>
              <el-date-picker
                class="expire-time-picker"
                :disabled="!expireFlag"
                v-model="entity.expireTime"
                type="datetime"
                placeholder="选择到期时间"></el-date-picker>
            </div>
          </div>
        </Card>

      </el-col>
      <el-col :span="14" :offset="1">
        <Card cardWidth='100%' :cardName="entity.imageType !== 2? '请选择站内文章': '请添加外链文章'" :scalable="false">
          <tool-bar
            v-if="entity.imageType == 1"
            slot="tool" class="tool-bar"
            @emptyQuery="emptyQuery"
            @receiveKeyword="receiveKeyword"></tool-bar>
          <div slot="content" class="content-box">
            <div class="input-item" v-show="entity.imageType == 1">
              <el-table
                ref="singleTable"
                :data="articleData"
                highlight-current-row
                @current-change="handleCurrentChange"
                :cell-style="cellStyle"
                :header-cell-style="headerCellStyle"
                style="width: 100%">
                <el-table-column
                  type="index"
                  width="50">
                </el-table-column>
                <el-table-column
                  property="title"
                  label="文章标题"
                  min-width="120">
                </el-table-column>
                <el-table-column
                  property="updateTime"
                  label="最后更新时间"
                  min-width="40">
                </el-table-column>
              </el-table>
              <pagination
                class="pagination"
                :total="total"
                :pageSize="3"
                @getCurrentPage="getCurrentPageFromPagination"></pagination>
            </div>
            <div class="input-item" v-show="entity.imageType == 1">
              <h3 :class="entity.aid?'h3-selected': 'h3-not-selected'">{{!entity.aid? '未选择文章': '已选文章'}}</h3>
              <el-tag class="selected-article" type="primary" v-show="entity.aid != null">
                {{selectedMessage}}
              </el-tag>
              <el-button type="info" size="small" class="cancel-select" v-show="entity.aid" @click="clearSelection">取消选择</el-button>
            </div>
            <div class="input-item" v-show="entity.imageType == 2">
              <h3 class="h3-title">文章标题</h3>
              <el-input
                @focus="focusTitleInput"
                @blur="blurTitleInput"
                class="input-title"
                v-model="entity.outerArticleTitle"
                maxlength="100"></el-input>
              <span :class="titleTipFlag?'tip showTip': 'tip'">最大长度为100个字符</span>
              <span class="star">*</span>
            </div>
            <div class="input-item" v-show="entity.imageType == 2">
              <h3 class="h3-url">外链地址</h3>
              <el-input
                @focus="focusUrlInput"
                @blur="blurUrlInput"
                class="input-url"
                v-model="entity.outerArticleUrl"
                maxlength="500"></el-input>
              <span :class="urlTipFlag?'tip showTip': 'tip'">最大长度为500个字符</span>
              <span class="star">*</span>
            </div>
            <div class="input-item" v-show="entity.imageType == 2">
              <h3 class="h3-upload">图片上传</h3>
              <span class="star">*</span>
              <el-upload
                class="avatar-uploader"
                action="http://api.tsinglog.online/upload/uploadImage"
                :headers="myHeaders"
                :show-file-list="false"
                :on-success="handleAvatarSuccess">
                <i class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
            <div class="input-item input-item-preview" v-show="entity.imageType == 1">
              <h3 class="h3-preview">图片预览</h3>
              <el-image
                class="image-preview"
                style="width: 700px; height: 300px; margin-left: 20px;"
                :src="entity.imagePreviewUrlLocal"
                fit="contain">
                <div slot="error" class="image-slot save-image">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
              <div class="button-box">
                <el-button type="info" @click="$router.go(-1)">返回</el-button>
                <el-button type="primary" @click="saveCarouselImage">保存</el-button>
              </div>
            </div>
            <div class="input-item input-item-preview" v-show="entity.imageType == 2">
              <h3 class="h3-preview">图片预览</h3>
              <el-image
                class="image-preview"
                style="width: 700px; height: 300px; margin-left: 20px;"
                :src="entity.imagePreviewUrlOuter"
                fit="contain">
                <div slot="error" class="image-slot save-image">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
              <div class="button-box">
                <el-button type="info" @click="$router.go(-1)">返回</el-button>
                <el-button type="primary" @click="saveCarouselImage">保存</el-button>
              </div>
            </div>
          </div>
        </Card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import Card from 'components/common/card/Card';
  import Pagination from 'components/common/pagination/Pagination';
  import ToolBar from 'components/content/toolbar/ToolBar';

  import {getArticleDataForSave} from "../../../network/viewsRequest/article";
  import {insertCarouselImage, getCarouselImageById, updateCarouselImage} from "../../../network/viewsRequest/carousel";
  import {GMTToStr} from "../../../common/date";

  import {IMAGE_SERVER_URL} from "../../../common/const";

  export default {
    name: "SaveImageView",
    components: {
      Card,
      Pagination,
      ToolBar
    },
    data() {
      return {
        entity: {
          id: 0,
          imageType: '1',
          usable: 1,
          sort: 1,
          aid: null,
          outerArticleTitle: '', //外链文章标题
          outerArticleUrl: '', // 外链文章链接
          imagePreviewUrlLocal: '', // 本站文章对应的图片预览的地址
          imagePreviewUrlOuter: '', // 外链文章对应的图片预览的地址
          expireTime: null, // 自动到期时间
        },
        query: {
          currentPage: 1,
          keyword: ''
        },
        articleData: [],
        total: 0,
        expireFlag: false, // 是否自动过期，默认为false
        titleTipFlag: false, // 是否显示文章标题上的提示信息
        urlTipFlag: false, // 是否显示链接上的提示信息
        sortTipFlag: false, // 是否显示排序上的提示信息
        selectedMessage: '', // 选择站内文章后的显示信息，如果没有选择，那么显示‘尚未选择’
        myHeaders: {
          Authorization: `Bearer ${this.$store.state.token}`
        }
      }
    },
    methods: {
      /**
       * 设置表格中单元格的样式
       */
      cellStyle() {
        return {
          'padding': '7px'
        }
      },
      /**
       * 设置表头中单元格的样式
       */
      headerCellStyle() {
        return {
          'padding': '0px'
        }
      },
      /**
       * 初始化搜索条件
       */
      emptyQuery() {
        this.query = {
          currentPage: 1,
          keyword: ''
        };
        this.getArticleDataForSave();
      },
      /**
       * 接收toolbar的关键字
       */
      receiveKeyword(keyword) {
        this.query.currentPage = 1;
        this.query.keyword = keyword;
        this.getArticleDataForSave();
      },
      /**
       * 点击取消选择按钮时调用的方法，将当前选择的信息全部清空
       */
      clearSelection() {
        this.selectedMessage = '';
        this.entity.aid = null;
        this.entity.imagePreviewUrl = '';
        this.setCurrent();
      },
      /**
       * 点击表格行时触发的方法
       */
      handleCurrentChange(row) {
        if (row !== null) {
          // 将当前行中的id值传递给entity中的aid
          this.entity.aid = row.id;
          // 给图片预览赋值
          this.entity.imagePreviewUrlLocal = IMAGE_SERVER_URL + row.coverImage;
          // 给el-tag赋值
          this.selectedMessage = row.title;
        }
      },
      /**
       * 点击分页插件调用的方法
       */
      getCurrentPageFromPagination(page) {
        this.query.currentPage = page;
        this.getArticleDataForSave();
      },
      /**
       * 图片排序输入框获取焦点时调用的方法
       */
      focusSortInput() {
        this.sortTipFlag = true;
      },
      /**
       * 图片排序输入框失去焦点时调用的方法
       */
      blurSortInput() {
        this.sortTipFlag = false;
      },
      /**
       * 文章标题输入框获取焦点时调用的方法
       */
      focusTitleInput() {
        this.titleTipFlag = true;
      },
      /**
       * 文章标题输入框失去焦点时调用的方法
       */
      blurTitleInput() {
        this.titleTipFlag = false;
      },
      /**
       * 文章链接输入框获取焦点时调用的方法
       */
      focusUrlInput() {
        this.urlTipFlag = true;
      },
      /**
       * 文章链接输入框失去焦点时调用的方法
       */
      blurUrlInput() {
        this.urlTipFlag = false;
      },
      /**
       * 保存轮播图片
       */
      saveCarouselImage() {
        // 1.处理相关数据
        let entity = this.removeRedundancyProperty();
        // 2.校验数据
        if (!this.checkSaveData(entity)) {
          return false;
        }
        // 3.进行保存
        this.saveCarouselImageLogic(entity);
      },
      /**
       * 处理相关数据，分为去掉不需要的属性，和对imagePreviewUrl的处理
       * 1.保存前先去除不需要使用的属性，具体逻辑为
       *    id: 都要
       *    imageType: 都要
       *    sort: 都要
       *    usable: 都要
       *    aid: 本站文章要
       *    outerArticleTitle: 外链文章要
       *    outerArticleUrl: 外链文章要
       *    imagePreviewUrlOuter: 外链文章要
       *    expireTime: 都要
       * 2.对imagePreviewUrl的处理
       *    去掉前面的路径，比如
       *        http://localhost:9090/image/5/D/5D75D721FA7542C5A24C172CA1A16551.jpg
       *    需要保存为
       *        /5/D/5D75D721FA7542C5A24C172CA1A16551.jpg
       */
      removeRedundancyProperty() {
        let type = this.entity.imageType;

        let entity = {};
        entity.id = this.entity.id;
        entity.imageType = type;
        entity.sort = this.entity.sort;
        entity.usable = this.entity.usable;
        if (this.entity.expireTime != null) {
          entity.expireTime = GMTToStr(this.entity.expireTime);
        }

        if (type == 1) {
          entity.aid = this.entity.aid;

        } else {
          entity.outerArticleTitle = this.entity.outerArticleTitle;
          entity.outerArticleUrl = this.entity.outerArticleUrl;
          let imagePreviewUrlOuter = this.entity.imagePreviewUrlOuter;
          imagePreviewUrlOuter = imagePreviewUrlOuter.substring((IMAGE_SERVER_URL).length);
          entity.imagePreviewUrl = imagePreviewUrlOuter;
        }

        return entity;
      },
      /**
       * 保存前校验数据是否合法
       */
      checkSaveData(entity) {
        // console.log(entity);
        let type = entity.imageType;

        if (type == 1) {
          if (entity.aid == null) {
            this.$message.error("请选择加入轮播图的文章");
            return false;
          }
        } else {
          if (entity.outerArticleTitle == null || entity.outerArticleTitle == '') {
            this.$message.error("请输入外链文章的标题");
            return false;
          }
          if (entity.outerArticleUrl == null || entity.outerArticleUrl == '') {
            this.$message.error("请输入外链文章的地址");
            return false;
          }
          if (entity.imagePreviewUrl == null || entity.imagePreviewUrl == '') {
            this.$message.error("请上传轮播图图片");
            return false;
          }
        }
        return true;
      },
      /**
       * 保存图片的具体逻辑
       * @param entity 需要保存的信息
       */
      saveCarouselImageLogic(entity) {

        // 1.选择方法
        let func = null;
        if (this.entity.id != 0) {
          func = updateCarouselImage;
        } else {
          func = insertCarouselImage;
        }

        // 2.进行保存
        this.$confirm('确定要进行保存吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }).then(() => {
          func(entity).then(res => {
            if (res.code == 1) {
              this.$message.success("保存成功！");
              this.$router.push("/dashboard/carousel");
            } else {
              this.$message.error(res.message);
            }
          })
        }).catch(() => {
          this.$message.info("保存操作已经被取消");
        });
      },
      /**
       * 图片上传成功时调用的方法
       */
      handleAvatarSuccess(res, file) {
        // this.imageUrl = URL.createObjectURL(file.raw);
        this.entity.imagePreviewUrlOuter = IMAGE_SERVER_URL + res.data.imgUrl;
      },
      /**
       * 1.获取saveImageView中表格的文章数据，它需要符合两个条件
       *    1.1.文章已经启用
       *    1.2.文章还没有被添加为轮播图
       * 2.如果url中id参数有值，再回显信息
       */
      // TODO 用Promise分离
      getArticleDataForSave() {
        getArticleDataForSave(this.query).then(res => {
          if (res.code == 1) {
            this.articleData = res.data.items;
            this.total = res.data.total;

            // 回显信息
            let id = this.$route.query.id;
            if (id) {
              getCarouselImageById(id).then(res => {
                let detail = res.data;

                this.entity.id = detail.id;
                this.entity.imageType = detail.type;
                this.entity.sort = detail.sort;

                if (detail.expireTime) {
                  this.entity.expireTime = detail.expireTime;
                  this.expireFlag = true;
                }

                if (detail.type == 1) { // 站内文章
                  this.entity.aid = detail.aid;
                  this.selectedMessage = detail.articleTitle;
                  // TODO 没搞懂为什么这里必须延时后才能正常加载图片，不延时this.entity.imagePreviewUrl这个属性都不能被赋值
                  window.setTimeout(() => {
                    this.entity.imagePreviewUrlLocal = detail.picUrl;
                  }, 100);
                } else { // 外链文章
                  this.entity.outerArticleTitle = detail.articleTitle;
                  this.entity.outerArticleUrl = detail.articleLink;
                  // TODO 没搞懂为什么这里必须延时后才能正常加载图片，不延时this.entity.imagePreviewUrl这个属性都不能被赋值
                  window.setTimeout(() => {
                    this.entity.imagePreviewUrlOuter = detail.picUrl;
                  }, 100);
                }
              });
            }
          } else {
            this.articleData = [];
            this.total = 0;
          }
        })
      },
      /**
       * 设置表格中当前选择哪一行的数据
       * @param row 该行数据
       */
      setCurrent(row) {
        this.$refs.singleTable.setCurrentRow(row);
      },
    },
    mounted() {
      this.getArticleDataForSave();
    }
  }
</script>

<style scoped>
  .pagination {
    width: 100%;
    float: none;
    text-align: right;
    height: 40px;
  }
  .tool-bar {
    display: block;
    text-align: right;
    margin-right: 160px;
  }
  .el-radio-group {
    margin-bottom: 20px;
    margin-left: 10px;
    margin-top: 10px;
  }
  .radio-box {
    margin-left: 10px;
    margin-top: -10px;
  }
  .input-sort {
    margin-left: 10px;
    width: 220px;
  }
  .expire-checkbox {
    display: block;
    margin-left: 10px;
    margin-bottom: 10px;
  }
  .expire-time-picker {
    margin-left: 10px;
  }
  h3 {
    color: #666;
  }
  .h3-type,.h3-expire {
    display: block;
    margin-bottom: 10px;
  }
  .h3-title,.h3-url,.h3-upload,.h3-preview,.h3-selected,.h3-not-selected {
    display: inline-block;
    vertical-align: middle;
  }
  .h3-selected,.h3-not-selected {
    margin-right: 20px;
  }
  .h3-selected {
    color: #409EFF;
  }
  .h3-not-selected {
    color: #F56C6C;
  }
  .h3-preview {
    vertical-align: top;
  }
  .button-box {
    text-align: right;
  }
  .selected-article {
    display: inline-block;
    vertical-align: middle;
  }
  .input-title,.input-url {
    display: inline-block;
    width: 700px;
    margin-left: 20px;
    vertical-align: middle;
  }
  .content-box {
    width: 95%;
    margin: 0 auto;
  }
  .cancel-select {
    margin-left: 10px;
  }
  .tip {
    display: block;
    margin-left: 95px;
    font-size: 14px;
    margin-top: -10px;
    color: #F56C6C;
    visibility: hidden;
  }
  .showTip {
    visibility: visible !important;
  }
  .tip-sort {
    margin-left: 10px;
    margin-top: -5px;
    line-height: 30px;
  }
  .star {
    position: absolute;
    color: #F56C6C;
    font-size: 18px;
    top: -2px;
    left: 78px;
  }
  .sort-star {
    left: 95px;
  }
  .input-item {
    position: relative;
    line-height: 44px;
    padding: 0;
  }
  .input-item:first-child,input-item:nth-child(4) {
    margin-top: 0;
  }
  .input-item-preview {
    margin-top: 20px;
  }
  .config-box {
    margin-top: 20px;
  }
  .avatar-uploader {
    display: inline-block;
    vertical-align: top;
    margin-left: 20px;
  }

  .image-preview {
    background-color: #fff;
    border-radius: 6px;
  }

</style>

<style>
  .image-slot {
    display: block;
    width: 100%;
    height: 300px;
    font-size: 28px;
    line-height: 300px;
    text-align: center;
    border: 1px dashed #e0e0e0;
    border-radius: 6px;
  }
  .el-image__inner {
    border-radius: 6px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #aaa;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    vertical-align: bottom;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 110px;
    height: 110px;
    line-height: 110px;
    text-align: center;
  }
  .avatar {
    width: 110px;
    height: 110px;
    display: block;
  }
</style>
